package com.wuwei.elearning.question.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.elearning.question.dao.DataDAO;
import com.wuwei.elearning.question.domain.Question;
import com.wuwei.elearning.question.listener.UploadDataListener;
import com.wuwei.elearning.question.mapper.QuestionMapper;
import com.wuwei.elearning.question.service.QuestionService;
import com.wuwei.elearning.utils.RecordUtils;
import com.wuwei.elearning.utils.token.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 保存题目信息的表，不管是机型题，基础执照题，还是英语题，都保存在该表中 服务实现类
 * </p>
 *
 * @author wuwei
 * @since 2024-01-20
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {


    @Resource
    private DataDAO<Question> toolDataDAO;

    @Resource
    private QuestionMapper questionMapper;

    @Override
    @Transactional
    public void upload(InputStream inputStream, Long account,Long subjectId) {
        EasyExcel.read(inputStream,Question.class,new UploadDataListener<Question>(toolDataDAO)).sheet().doRead();
        List<Question> list = toolDataDAO.getList();
        log.info("上传题目的总数为："+list.size());
        try {
            list.forEach(q -> {
                // 验证逻辑
                validateQuestion(q);

                q.setSubjectId(subjectId);
                q.setCreatedBy(account);
                q.setCreatedTime(LocalDateTime.now());
                questionMapper.insert(q);
            });
        } finally {
            // 确保在任何情况下都会清空列表
            list.clear();
        }
    }

    @Resource
    private RecordUtils recordUtils;

    @Override
    @Transactional
    public void updateQuestion(Question question, Long account) {
        Question question1 = questionMapper.selectById(question.getId());
        recordUtils.recordQuestionChange(question1,question,account);
        question.setUpdatedBy(account);
        question.setUpdatedTime(LocalDateTime.now());
        questionMapper.updateById(question);
    }

    // 建议添加校验方法
    private void validateQuestion(Question q) {
        if (!q.getItem1().startsWith("A.")) {
            throw new IllegalArgumentException("选项1必须以A.开头");
        }
        if (!q.getItem2().startsWith("B.")) {
            throw new IllegalArgumentException("选项2必须以B.开头");
        }
        if (!q.getItem3().startsWith("C.")) {
            throw new IllegalArgumentException("选项3必须以C.开头");
        }
        if (!q.getItem4().startsWith("D.")) {
            throw new IllegalArgumentException("选项4必须以D.开头");
        }

        // 验证答案格式
        String answer = q.getAnswer();
        if (answer.length() == 1) {
            if (!"ABCD".contains(answer)) {
                throw new IllegalArgumentException("单选题答案必须是A、B、C、D之一");
            }
        } else {
            // 多选题答案验证
            String[] answers = answer.split("\\+");
            // 验证答案排序和格式
            String sortedAnswer = Arrays.stream(answers)
                    .sorted()
                    .collect(Collectors.joining("+"));
            if (!answer.equals(sortedAnswer)) {
                throw new IllegalArgumentException("多选题答案必须按A、B、C、D顺序排列，并用+号分隔");
            }
        }
    }
}
